package com.mxcyk.serviceLogic;

import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.Graphics;
import java.awt.color.ColorSpace;
import javax.imageio.ImageIO;
import javax.swing.*;
/**
 * 功能：改变图片大小
 * @author k
 *
 */
public class ChangeImageSize {
	/**
	 * 缩放图像
	 * 
	 * @param srcImageFile
	 *            源图像文件地址
	 *@param width
	 *            缩放后的图像宽度 
	 *@param height
	 *            缩放后的图像高度          
	 */
	static Image image=null;
	public static Image getImage() {
		return image;
	}
	
	public static Image scale(Image srcImage, int width,int height ) {
		
			BufferedImage src = toBufferedImage(srcImage);
				//ImageIO.read(new File(srcImageFile)); // 读入文件
			// 图宽Width;图长Height;
			
			image = src.getScaledInstance(width, height,
					Image.SCALE_DEFAULT);
			BufferedImage tag = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics g = tag.getGraphics();
			g.drawImage(image, 0, 0, null); // 绘制缩小后的图
			g.dispose();
			//ImageIO.write(tag, "JPEG", new File(result));// 输出到文件
			return image;

	}

	public static BufferedImage toBufferedImage(Image image) {
		if (image instanceof BufferedImage) {
			return (BufferedImage) image;
		}
		
		image = new ImageIcon(image).getImage();
		BufferedImage bimage = null;
		GraphicsEnvironment ge = GraphicsEnvironment
				.getLocalGraphicsEnvironment();
		try {
			int transparency = Transparency.OPAQUE;

			GraphicsDevice gs = ge.getDefaultScreenDevice();
			GraphicsConfiguration gc = gs.getDefaultConfiguration();
			bimage = gc.createCompatibleImage(image.getWidth(null), image
					.getHeight(null), transparency);
		} catch (HeadlessException e) {
			// The system does not have a screen
		}
		if (bimage == null) {
			// Create a buffered image using the default color model
			int type = BufferedImage.TYPE_INT_RGB;
			
			bimage = new BufferedImage(image.getWidth(null), image
					.getHeight(null), type);
		}
		// Copy image to buffered image
		Graphics g = bimage.createGraphics();
		// Paint the image onto the buffered image
		g.drawImage(image, 0, 0, null);
		g.dispose();
		return bimage;
	}
		
	

	/** */
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//scale("G:/temp/1.jpg",50,50);
	}
}
